package com.backpackerxl.blog.web;

import com.backpackerxl.blog.service.BlogsService;
import com.backpackerxl.blog.service.TagService;
import com.backpackerxl.blog.service.TypeService;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * Author by：Backpackersxl
 * Date: 2021/5/2/002
 * Time: 15:12
 **/
@Controller
public class HomeController {
    private final BlogsService blogsService;

    private final TypeService typeService;

    private final TagService tagService;

    public HomeController(BlogsService blogsService, TypeService typeService, TagService tagService) {
        this.blogsService = blogsService;
        this.typeService = typeService;
        this.tagService = tagService;
    }

    @RequestMapping("/")
    public String index(@PageableDefault(size = 6, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
                        Model model) {
        model.addAttribute("page", blogsService.listBlog(pageable));
        model.addAttribute("types", typeService.listTypeTop(6));
        model.addAttribute("tags", tagService.listTagTop(10));
        model.addAttribute("recommendBlogs", blogsService.listBlognew(6));
        return "home";
    }

    @PostMapping("/search")
    public String search(@PageableDefault(size = 6, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
                         @RequestParam String query, Model model) {
        model.addAttribute("page", blogsService.listBlogSearch("%" + query + "%", pageable));
        model.addAttribute("query", query);
        return "search";
    }

    @RequestMapping("/blog/{id}")
    public String blog(@PathVariable Long id, Model model, HttpServletRequest request) {
        model.addAttribute("blog", blogsService.getAndConvert(id, request));
        return "blog";
    }

    @GetMapping("/footer/newblog")
    public String newblogList(Model model) {
        model.addAttribute("footer", blogsService.listBlognew(3));
        return "_fragments :: blogLists";
    }
}
